package com.bjpowernode.services;
import com.bjpowernode.beans.NewsType;
import com.bjpowernode.dao.NewsTypeDao;
import com.bjpowernode.dao.NewsTypeDaoImp;
import com.bjpowernode.exception.MyException;
import org.apache.commons.lang3.ObjectUtils;
import java.sql.SQLException;
import java.util.ArrayList;

public class NewsTypeServicesImp implements NewsTypeServices {

    NewsTypeDao newsTypeDao = new NewsTypeDaoImp();


    //DQL不需要解析SQLException
    @Override
    public ArrayList<NewsType> getAll() throws SQLException {
        ArrayList<NewsType> all = newsTypeDao.getAll();
        return all;
    }

    @Override
    public NewsType get(int id) throws SQLException {
        NewsType newsType = newsTypeDao.get(id);
        return newsType;
    }

    //DML需要解析SQLException
    @Override
    public void add(NewsType newsType) throws MyException {
        //判断空字符串
        String name = newsType.getName();
        boolean empty = false;
        empty = ObjectUtils.allNull(name);
        if (empty) {
            throw new MyException("名称不能为null");
        }
        empty = ObjectUtils.isEmpty(name.trim());
        if (empty) {
            throw new MyException("名称不能为空");
        }
        try {
            newsTypeDao.add(newsType);
        } catch (SQLException e) {

            if (e.getMessage().indexOf("Data too long for column 'name'") != -1) {
                throw new MyException("名称的长度只能是1-200");
            }
            if ((e.getMessage().indexOf("Duplicate entry") != -1) && (e.getMessage().indexOf("for key 'name'") != -1)) {
                throw new MyException("名称不能重复");
            }
        }
    }

    @Override
    public void edit(NewsType newsType) throws SQLException, MyException {
//判断空字符串
        String name = newsType.getName();
        boolean empty = false;
        empty = ObjectUtils.allNull(name);
        if (empty) {
            throw new MyException("名称不能为null");
        }
        empty = ObjectUtils.isEmpty(name.trim());
        if (empty) {
            throw new MyException("名称不能为空");
        }
        try {
            newsTypeDao.edit(newsType);
        } catch (SQLException e) {

            if (e.getMessage().indexOf("Data too long for column 'name'") != -1) {
                throw new MyException("名称的长度只能是1-200");
            }
            if ((e.getMessage().indexOf("Duplicate entry") != -1) && (e.getMessage().indexOf("for key 'name'") != -1)) {
                throw new MyException("名称不能重复");
            }
        }
    }

    @Override
    public void del(int id) throws SQLException, MyException {
        newsTypeDao.del(id);
    }
}
